package edu.cmu.cs.cs214.hw9.client.controllers.eventhandlers;

import java.util.List;

import javax.swing.SwingWorker;

import edu.cmu.cs.cs214.hw9.client.controllers.BackendCacheAdapter;
import edu.cmu.cs.cs214.hw9.client.controllers.SessionController;
import edu.cmu.cs.cs214.hw9.client.gui.NewsFeedScreen;
import edu.cmu.cs.cs214.hw9.datatypes.Status;
import edu.cmu.cs.cs214.hw9.datatypes.User;

/**
 * Goes to the logged-in user's news feed. 
 */
public class GotoFeedHandler extends SessionEventHandler {
	/**
	 * Obtain news feed data in a separate thread to prevent swing from freezing.
	 */
	private class FeedWorker extends SwingWorker<List<Status>, Void> {
		private BackendCacheAdapter model;
		private User currentUser;
		
		/**
		 * Constructs a news feed data request.
		 */
		public FeedWorker() {
			currentUser = controller.getCurrentUser();
			model = controller.getModel();
		}
		
		/**
		 * Obtains the most recent friends' statues from the database.
		 * 
		 * @return Friends' most recent 10 statuses. Note that list may be empty.
		 */
		public List<Status> doInBackground() {
			return model.getMostRecentFriendUpdates(currentUser, 10);
		}
		
		/**
		 * Redirects the user to the newsfeed page.
		 */
		public void done() {
			try {
				List<Status> statusList = get();
				changeScreen(new NewsFeedScreen(statusList));
			} catch (Exception e) {
				throw new RuntimeException("Fatal error occured when switching to the news feed: " + e.getMessage());
			}
		}
	};
	
	/**
	 * Set the current session controller to the provided controller.
	 * 
	 * @param controller Controller to associate with this event handler.
	 */
	public GotoFeedHandler(SessionController controller) { super(controller); }
	
	/**
	 * Create the goto news feed request and run it in an outside thread.
	 * 
	 * @param param Friend to post, as a User object.
	 */
	public void handleEvent(Object param) {
		FeedWorker feedWorker = new FeedWorker();
		feedWorker.execute();
	}
}
